package com.fms.fmsapi.common.config;

import com.fms.fmsapi.common.JacksonObjectMapper;
import com.fms.fmsapi.common.handler.AuthInterceptor;
import com.fms.fmsapi.common.handler.CrosInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Slf4j
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public AuthInterceptor authInterceptor(){
        return new AuthInterceptor();
    }

    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CrosInterceptor());
        log.info("注册Cors拦截器");
        registry.addInterceptor(authInterceptor())
                .excludePathPatterns("/auth/code")
                .excludePathPatterns("/auth/login");
        log.info("注册Auth拦截器");
    }

    /**
     * 装载消息转换器，之前直接在消息转换器上写@componet注解，其实是替换了原有的转换器，而这种方式则是在消息转换器列表插入，这样即使自定义的报错了
     * 也能够使用框架自带的转换器
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        converters.add(0, messageConverter);//放在第一位
    }
}
